<?php
namespace App\Http\Controllers\FrontEnd;

use App\Http\Controllers\Controller;
use App\Models\MBdzxLog;
use App\Models\MBonusLog;
use App\Models\MConsumeLog;
use App\Models\MNotices;
use App\Models\MProtocols;
use App\Models\MRemitLog;
use App\Models\MSwitchCoinLog;
use App\Models\MTransferLog;
use App\Models\MUser;
use App\Models\MUserAttr;
use App\Models\MVip_award;
use App\Models\MVip_up_log;
use App\Models\MWallet;
use App\Models\MWithdrawLog;
use App\Templates\ActivationUserAct;
use App\Templates\DelUserAct;
use App\Templates\RegUserAct;
use App\Utils\GDUtil;
use App\Utils\QRUtil;
use App\Utils\TreeUtil;
use App\VModels\VVip;
use DB;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Mail;

/**
 * 会员控制器
 */
class UserController extends Controller
{
    use RegUserAct, ActivationUserAct, DelUserAct;

    /**
     * 会员登录界面
     */
    public function loginPage()
    {
        $this->data['theme'] = loginTheme();
        return view('web.login')->with($this->data);
    }

    /**
     * 用户登录验证
     */
    public function loginAct(Request $request)
    {
        if (!$this->validateReq($request, MUser::loginRulesWithMsg(0), MUser::loginRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //验证码检查
        if (!GDUtil::checkCode(GDUtil::$USER_CODE, $request->yzm)) {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "验证码效验失败！");
            return response()->json($this->data);
        }

        //账号密码检查
        $user = MUser::where("username", strtolower($request->username))
            ->where("userpass", $request->userpass)->first();
        if (empty($user)) {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "账号密码验证失败！");
            return response()->json($this->data);
        }

        $user->loginStatus()->loginLog();
        $this->data = $this->makeJsCode(0, "登录成功！");
        return response()->json($this->data);
    }

    /**
     * 我的个人主页页面
     */
    public function centerPage(Request $request)
    {
        $this->data['user'] = MUser::find(ss('uid'));
        $this->data['notices'] = MNotices::select(['id', 'title', 'content', 'time', 'start', 'end'])
            ->where('start', '<', time())
            ->where('end', '>', time())
            ->orderBy("time", "desc")
            ->skip(0)->take(5)
            ->get();

        return view("web.center")->with($this->data);
    }

    /**
     * 奖金记录页面
     * @$param $type 1为编号搜索  2会员搜索
     */
    public function bonusPage(Request $request, $index = 1)
    {
        $query = (new MBonusLog())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            } elseif ($type == 2) {
                $query = $query->where("username", $request->search);
            }

        }

        $this->fyInit(route("web.bonus"), 20)->fyCalc(MBonusLog::where('uid', ss('uid'))->count(), $index);

        $bonus = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)->get();
        $this->data['logs'] = $bonus;

        $this->fyViewInit($this->data);
        return view('web.bonus')->with($this->data);
    }

    /**
     * 消费记录页面
     */
    public function shoppingPage(Request $request, $index = 1)
    {
        $query = (new MConsumeLog())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            } elseif ($type == 2) {
                $query = $query->where("username", $request->search);
            }

        }

        $this->fyInit(route('web.shopping'), 5)->
        fyCalc(MConsumeLog::where('uid', ss('uid'))->count(), $index);
        $logs = $query->orderBy('time', 'desc')
            ->skip($this->fy_pgOffset)->take($this->fy_pgSize)->get();
        $this->data['logs'] = $logs;

        $this->fyViewInit($this->data);
        return view('web.shopping')->with($this->data);
    }

    /**
     * 会员转账页面
     */
    public function transferPage()
    {
        $this->data['wallet'] = MWallet::where('uid', ss('uid'))->first();
        return view('web.transfer')->with($this->data);
    }

    /**
     * 会员转账处理
     */
    public function transferAct(Request $request)
    {

//        if (count($request->rule) > 0) {//验证自动添加的属性规则
//            for ($i = 0; $i < count($request->rule); $i++) {
//                $rule = unserialize($request->rule[$i]);
//                $msg = unserialize($request->msg[$i]);
//                if (!$this->validateReq($request, $rule, $msg)) {
//                    $this->data = $this->makeJsCode(1, $this->errors->first());
//                    return response()->json($this->data);
//                }
//            }
//        }
        if (cv("switch.transfer") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        //对会员转账信息进行验证
        if (!$this->validateReq($request, MWallet::transferValidate(0), MWallet::transferValidate(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }
        //检查接收用户（已激活）是否存在，并且不能给自己转账
        $accept_user = MUser::where('username', strtolower($request->accept_user))->where('ok_status', MUser::$STATUS_ACTIVATED)->first();

        if (empty($accept_user)) {
            $this->data = $this->makeJsCode(1, "接收用户不存在!");
            return response()->json($this->data);
        }

        if (strtolower(ss('uname')) == strtolower($accept_user->username)) {
            $this->data = $this->makeJsCode(1, "不能给自己转账!");
            return response()->json($this->data);
        }

        //检查接收用户是否是团队内的人 (暂定)

        //检查转账金额是否合法
        if (!preg_match("/^[1-9]\d*00$/", $request->money, $match)) {
            $this->data = $this->makeJsCode(1, "转账金额必须为100的整数倍！");
            return response()->json($this->data);
        }

        //检查交易密码
        $me = MUser::find(ss('uid'));
        if ($request->safepass != $me->safepass) {
            $this->data = $this->makeJsCode(1, "交易密码错误!");
            return response()->json($this->data);
        }

        $me_wallet = $me->wallet;
        //检查钱包余额是否充足
        if ($request->wallet == MWallet::$WALLET_TYPE_1 && $request->money > $me_wallet->w1) {
            $this->data = $this->makeJsCode(1, "奖金币余额不足！");
            return response()->json($this->data);
        } elseif ($request->wallet == MWallet::$WALLET_TYPE_2 && $request->money > $me_wallet->w2) {
            $this->data = $this->makeJsCode(1, "报单币余额不足！");
            return response()->json($this->data);
        } elseif ($request->wallet == MWallet::$WALLET_TYPE_3 && $request->money > $me_wallet->w3) {
            $this->data = $this->makeJsCode(1, "购物币余额不足！");
            return response()->json($this->data);
        }

        //进行转账操作
        try {
            DB::transaction(function () use (&$me, &$me_wallet, &$accept_user, &$request) {
                if (MWallet::transferMoney($me, $me_wallet, $accept_user, $accept_user->wallet,
                        $request->wallet, $request->money) && MUserAttr::userInfo($me->id, $request->all())
                ) {
                    $this->data = $this->makeJsCode(0, "转账成功！");
                } else {
                    $this->data = $this->makeJsCode(1, "转账失败！");
                }
            });
        } catch (Exception $exception) {
            $this->data = $this->makeJsCode(1, "转账失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 转账日志
     */
    public function tranLogPage(Request $request, $index = 1)
    {
        $query = (new MTransferLog())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type) && !empty($request->search)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            } elseif ($type == 2) {
                $query = $query->where("username", $request->search);
            }

        }


        //开启分页
        $this->fyInit(route("web.transfer.log"), 20)->fyCalc(MTransferLog::where('uid', ss('uid'))
            ->orWhere('accept_id', ss('uid'))->count(), $index);
        $this->data['transferLogs'] = $query
            ->orWhere('accept_id', ss('uid'))
            ->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('time', 'desc')
            ->get();
        $this->fyViewInit($this->data);

        return view('web.transfer_logs')->with($this->data);
    }

    /**
     * 会员提现界面
     */
    public function withdrawPage()
    {
        $this->data['wallet'] = MWallet::where('uid', ss('uid'))->first();
        return view('web.withdraw')->with($this->data);
    }

    /**
     * 会员提现执行函数
     */
    public function withdrawAct(Request $request)
    {
        if (cv("switch.withdraw") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");

            return response()->json($this->data);
        }

        //对会员提现信息进行验证
//        if (!$this->validateReq($request, MWithdrawLog::withdrawRulMsg(0), MWithdrawLog::withdrawRulMsg(1))) {
//            $this->data = $this->makeJsCode(1, $this->errors->first());
//            return response()->json($this->data);
//        }

        $me = MUser::find(ss('uid'));
        $type = intval($request->type);  //提现的类型
        if ($type == MWithdrawLog::$PAY_TYPE_ZFB) {           //为支付宝
            //验证收款信息
            if ($request->alipay_no == '') {
                $this->data = $this->makeJsCode(1, "支付宝名称必须填写！");
                return response()->json($this->data);
            }

            $request_safepass = $request->alipay_safepass;
            $request_tel = $request->alipay_tel;
            $request_wallet = intval($request->alipay_wallet);
            $request_money = $request->alipay_money;
            $request_remark = $request->alipay_remark;
        } elseif ($type == MWithdrawLog::$PAY_TYPE_WX) {   //微信
            //验证收款信息
            if ($request->wechat_no == '') {
                $this->data = $this->makeJsCode(1, "微信号必须填写！");
                return response()->json($this->data);
            }

            $request_safepass = $request->wechat_safepass;
            $request_tel = $request->wechat_tel;
            $request_wallet = intval($request->wechat_wallet);
            $request_money = $request->wechat_money;
            $request_remark = $request->wechat_remark;

        } elseif ($type == MWithdrawLog::$PAY_TYPE_YHK) {  //银行卡
            //验证收款信息
            if ($request->card_no == '') {
                $this->data = $this->makeJsCode(1, "请必须填写您的银行卡号！");
                return response()->json($this->data);
            }
            if ($request->card_name == '') {
                $this->data = $this->makeJsCode(1, "请必须填写您的开户姓名！");
                return response()->json($this->data);
            }
            if ($request->card_bank == '') {
                $this->data = $this->makeJsCode(1, "请选择银行卡名称！");
                return response()->json($this->data);
            }
            if (preg_match("/^([1-9]{16}|[1-9]{19})$/", $request->card_no)) {
                $this->data = $this->makeJsCode(1, "请填写正确的银行卡号！");
                return response()->json($this->data);
            }

            $imgPath = null;
            $request_money = $request->card_money;
            if ($request_money == '') {
                $this->data = $this->makeJsCode(1, "请填写提现金额！");
                return response()->json($this->data);
            }

            $request_safepass = $request->card_safepass;
            $request_tel = $request->card_tel;
            $request_wallet = intval($request->card_wallet);
            $request_money = $request->card_money;
            $request_remark = $request->card_remark;

        }

//        $request_wallet 为钱包类型, $request_money为提现金额 ,$request_safepass 为交易密码,$request_tell,为手机号码,$request_remark 备注

        //交易密码验证
        if ($request_safepass !== $me->safepass) {
            $this->data = $this->makeJsCode(1, "交易密码验证失败！");
            return response()->json($this->data);
        }
        //手机号码
        if ($request_tel == '') {
            $this->data = $this->makeJsCode(1, "手机号码不能为空！");
            return response()->json($this->data);
        }

        //钱包类型
        if (empty($request_wallet)) {
            $this->data = $this->makeJsCode(1, "请选择钱包类型！");
            return response()->json($this->data);
        }

        if (!preg_match("/^[1-9]\d*00$/", $request_money, $match)) {
            $this->data = $this->makeJsCode(1, "提现金额只能是100的整数倍！");
            return response()->json($this->data);
        }

        //检查钱包余额是否充足
        $me_wallet = $me->wallet;

        if ($request_wallet == MWallet::$WALLET_TYPE_2 && sprintf("%.2f", $request_money) > sprintf("%.2f", $me_wallet->w2)) {

            $msg = "提现失败," . uWalletStr(MWallet::$WALLET_TYPE_2) . "余额不足!";

            $this->data = $this->makeJsCode(1, $msg);
            return response()->json($this->data);
        } elseif ($request_wallet == MWallet::$WALLET_TYPE_3 && sprintf("%.2f", $request_money) > sprintf("%.2f", $me_wallet->w3)) {

            $msg = "提现失败," . uWalletStr(MWallet::$WALLET_TYPE_3) . "余额不足!";

            $this->data = $this->makeJsCode(1, $msg);
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use (&$request_wallet, &$request_money, &$request, &$me, &$request_safepass, &$request_tel, &$request_remark) {
                if ($me->wallet->withdraw($request_wallet, $request_money) && MWithdrawLog::widthdraw($request_wallet, $request_money, $request, $me, $request_tel, $request_remark)) {
                    $this->data = $this->makeJsCode(0, "申请提现成功！");
                } else {

                    $this->data = $this->makeJsCode(1, "申请提现失败！");
                }
            });
        } catch (Exception $exception) {
            $this->data = $this->makeJsCode(1, "申请提现失败！");
        }

        return response()->json($this->data);


//        //检查是否是注册手机号
//        if ($me->mobile != $request->tel) {
//            $this->data = $this->makeJsCode(1, "当前手机号不是您的注册手机号!");
//            return response()->json($this->data);
//        }

        //检查提现验证码
//        $log = MSmsCode::where('mobile', $me->mobile)->where('sms_code', $request->code)->where('sms_is_used', 0)->first();
//        if (empty($log)) {
//            $this->data = $this->makeJsCode(1, "短信验证码错误！");
//            return response()->json($this->data);
//        }
//        if (strtotime($log->sms_close_time) < time()) {
//            $this->data = $this->makeJsCode(1, "短信验证码已过期，请重新获取！");
//            return response()->json($this->data);
//        }
//        $log->sms_is_used = 1;  //修改为已使用
//        $log->save();


    }


//    public function withdrawAct(Request $request)
//    {
////        if (count($request->rule) > 0) {//验证自动添加的属性规则
////            for ($i = 0; $i < count($request->rule); $i++) {
////                $rule = unserialize($request->rule[$i]);
////                $msg = unserialize($request->msg[$i]);
////                if (!$this->validateReq($request, $rule, $msg)) {
////                    $this->data = $this->makeJsCode(1, $this->errors->first());
////                    return response()->json($this->data);
////                }
////            }
////        }
//
//        //对会员提现信息进行验证
//        if (!$this->validateReq($request, MWithdrawLog::withdrawRulMsg(0), MWithdrawLog::withdrawRulMsg(1))) {
//            $this->data = $this->makeJsCode(1, $this->errors->first());
//            return response()->json($this->data);
//        }
//        MUserAttr::userInfo(1, $request);
//        //验证交易密码
//        $me = MUser::find(ss('uid'))->first();
//        if ($request->safepass != $me->safepass) {
//            $this->data = $this->makeJsCode(1, "交易密码验证失败！");
//            return response()->json($this->data);
//        }
//
//        //检查钱包余额是否充足
//        $me_wallet = $me->wallet;
//        if ($request->wallet == MWallet::$WALLET_TYPE_1 && $request->money > $me_wallet->w1) {
//            $this->data = $this->makeJsCode(1, "提现失败，奖金币余额不足");
//            return response()->json($this->data);
//        } elseif ($request->wallet == MWallet::$WALLET_TYPE_2 && $request->money > $me_wallet->w2) {
//            $this->data = $this->makeJsCode(1, "提现失败，报单币余额不足");
//            return response()->json($this->data);
//        } elseif ($request->wallet == MWallet::$WALLET_TYPE_3 && $request->money > $me_wallet->w3) {
//            $this->data = $this->makeJsCode(1, "提现失败，购物币余额不足");
//            return response()->json($this->data);
//        }
//
//        try {
//            DB::transaction(function () use (&$request, &$me, $me_wallet) {
//                if ($me_wallet->withdraw($request->wallet, $request->money, $request->intro) && MUserAttr::userInfo($me->id, $request->all())) {
//                    $this->data = $this->makeJsCode(0, "申请提现成功！");
//
//                } else {
//                    DB::rollBack();
//                    $this->data = $this->makeJsCode(1, "申请提现失败！");
//                }
//            });
//        } catch (Exception $exception) {
//            $this->data = $this->makeJsCode(1, "申请提现失败！");
//        }
//
//        return response()->json($this->data);
//    }

    /**
     * 提现日志界面
     */
    public function withdrawLogPage(Request $request, $index = 1)
    {

        $query = (new MWithdrawLog())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type) && !empty($request->search)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            }
//            elseif ($type == 2) {
//                $query = $query->where("username", $request->search);
//            }
        }
        //开启分页
        $this->fyInit(route("web.withdraw.log"), 5)->fyCalc($query->count(), $index);
        $this->data['withdrawLogs'] = $query
            ->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('create_time', 'desc')
            ->get();

        $this->fyViewInit($this->data);

        return view('web.withdraw_logs')->with($this->data);
    }

    /**
     * 撤销提现申请单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function withdrawLogCancel(Request $request, $id)
    {
        if (empty($id)) {
            return back()->with($this->makeJsCode(1, "参数错误！"));
        }
        $id = $request->id;
        try {
            DB::transaction(function () use ($id) {
                $log = MWithdrawLog::find($id);
                //退款提现金额
                $user = MUser::find(ss('uid'));
                $wallet = $user->wallet;
                if ($log->wallet == MWallet::$WALLET_TYPE_1) {
                    $wallet->w1 += $log->money;
                } elseif ($log->wallet == MWallet::$WALLET_TYPE_2) {
                    $wallet->w2 += $log->money;
                } elseif ($log->wallet == MWallet::$WALLET_TYPE_3) {
                    $wallet->w3 += $log->money;
                }
                //撤销记录
                MConsumeLog::log($user->id, $user->username, $log->money, MConsumeLog::$CONSUME_RECHARGE,
                    $log->wallet, "撤销提现申请单，退还" . uWalletStr($log->wallet) . " {$log->money} 元！");

                //删除记录
                if ($log->delete() && $wallet->save()) {
                    $this->data = $this->makeJsCode(0, "撤销成功，提现金额已到账！");
                } else {
                    $this->data = $this->makeJsCode(0, "撤销失败！");
                    DB::rollBack();
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作失败！");
        }
        return back()->with($this->data);
    }

    /**
     * 币种转换申请页
     */
    public function switchCoinPage()
    {
        $this->data['wallet'] = MWallet::where('uid', ss('uid'))->first();
        return view('web.switch_coin')->with($this->data);
    }

    /**
     * 币种转换执行函数
     */
    public function switchCoinAct(Request $request)
    {
        if (cv("switch.coin_switch") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        //对会员币种转换信息进行验证
        if (!$this->validateReq($request, MSwitchCoinLog::withdrawRulMsg(0), MSwitchCoinLog::withdrawRulMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //同币种之间禁止转换
        if ($request->real_coin == $request->final_coin) {
            $this->data = $this->makeJsCode(1, "同币种禁止转换! ");
            return response()->json($this->data);
        }

        //检查交易密码
        $me = MUser::find(ss('uid'));
        if ($request->safepass != $me->safepass) {
            $this->data = $this->makeJsCode(1, "交易密码错误!");
            return response()->json($this->data);
        }

        //检查钱包余额是否充足
        $wallet = $me->wallet;
        if ($request->real_coin == MWallet::$WALLET_TYPE_1 && $request->money > $wallet->w1) {
            $this->data = $this->makeJsCode(1, "转换失败，奖金币余额不足！");
            return response()->json($this->data);

        } elseif ($request->real_coin == MWallet::$WALLET_TYPE_2 && $request->money > $wallet->w2) {
            $this->data = $this->makeJsCode(1, "转换失败，报单币余额不足！");
            return response()->json($this->data);

        } elseif ($request->real_coin == MWallet::$WALLET_TYPE_3 && $request->money > $wallet->w3) {
            $this->data = $this->makeJsCode(1, "转换失败，购物币余额不足！");
            return response()->json($this->data);
        }

        if ($wallet->coinSwitch($request->real_coin, $request->final_coin, $request->money)) {
            MSwitchCoinLog::log($me->id, $request->real_coin, $request->final_coin, $request->money, 0, $request->money);
            $this->data = $this->makeJsCode(0, "币种转换成功！");
        } else {
            $this->data = $this->makeJsCode(1, "币种转换失败！");
        }

        return response()->json($this->data);
    }

    /**
     * 币种转换记录
     */
    public function switchLogPage(Request $request, $index = 1)
    {
        $query = (new MSwitchCoinLog())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type) && !empty($request->search)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            } elseif ($type == 2) {
                $query = $query->where("username", $request->search);
            }

        }

        //开启分页
        $this->fyInit(route("web.switch.log"), 20)->fyCalc(MSwitchCoinLog::where('uid', ss('uid'))->count(), $index);
        $this->data['switchLogs'] = $query
            ->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('time', 'desc')
            ->get();
        $this->fyViewInit($this->data);

        return view('web.switch_logs')->with($this->data);
    }

    public function remitApply()
    {
        $this->data['user'] = MUser::find(ss('uid'));
        $this->data['remits'] = MRemitLog::where("uid", ss('uid'))->get();
        return view('web.remit_apply')->with($this->data);
    }

    public function remitApplyPage($id)
    {
        $this->data['user'] = MUser::find(ss('uid'));
        $this->data['log'] = MRemitLog::where('id', $id)->where('uid', ss('uid'))->first();
        return view('web.remit_apply_page')->with($this->data);
    }

    /**
     * 验证并保存一条打款申请单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function remitSave(Request $request)
    {
        if (cv("switch.remit") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        //对打款申请单信息进行验证
        if (!$this->validateReq($request, MRemitLog::editRulesWithMsg(0), MRemitLog::editRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //检查打款金额
        if (!is_numeric($request->money) || $request->money <= 0) {
            $this->data = $this->makeJsCode(1, "打款金额请必须为大于0的数字！");
            return response()->json($this->data);
        }

        //检查交易密码
        $user = MUser::find(ss('uid'));
        if ($user->safepass !== $request->safepass) {
            $this->data = $this->makeJsCode(1, "交易密码输入错误！");
            return response()->json($this->data);
        }

//        $type = $request->remit_type; //申请打款的类型:支付宝,微信,银行卡
        if ($request->remit_type == MWallet::$PAY_TYPE_ZFB) {
            if (!$request->has(['alipay_no'])) {
                $this->data = $this->makeJsCode(1, "请输入支付宝账号！");
                return response()->json($this->data);
            }
        } elseif ($request->remit_type == MWallet::$PAY_TYPE_WX) {
            if (!$request->has(['wechat_no'])) {
                $this->data = $this->makeJsCode(1, "请输入微信账号！");
                return response()->json($this->data);
            }
        } elseif ($request->remit_type == MWallet::$PAY_TYPE_YHK) {
            if (!$request->has(['bank_no', 'bank_name', 'remitter'])) {
                $this->data = $this->makeJsCode(1, "请检查表单数据是否完善！");
                return response()->json($this->data);
            }
        }

        //打款申请单保存
        if (MRemitLog::saveRemitLog($request, $user)) {
            $this->data = $this->makeJsCode(0, "操作成功！");
            $this->data['id'] = MRemitLog::where('uid', ss('uid'))->orderBy('create_time', 'desc')->first()->id;
        } else {
            $this->data = $this->makeJsCode(1, "操作失败！");
        }

        return response()->json($this->data);
    }

    public function remitHasPay($id)
    {
        $log = MRemitLog::find($id);

        if ($log->uid !== ss('uid')) {
            $this->data = $this->makeJsCode(1, "信息验证失败！");
            return back()->with($this->data);
        }
        //检查状态
        if ($log->status !== 0) {
            $this->data = $this->makeJsCode(1, "此打款充值单已被处理！");
            return back()->with($this->data);
        }
        //改变status=1
        $log->status = 1;
        $log->pay_time = time();
        if ($log->save()) {
            $this->data = $this->makeJsCode(0, '操作成功');
        } else {
            $this->data = $this->makeJsCode(0, '操作失败');
        }

        return back()->with($this->data);
    }

    public function remitLogs(Request $request, $index = 1)
    {
        $query = (new MRemitLog())->query();
        $query = $query->where('uid', ss('uid'));

        $type = intval($request->type);
        if (!empty($type) && !empty($request->search)) {
            if ($type == 1) {
                $query = $query->where("no", $request->search);
            } elseif ($type == 2) {
                $query = $query->where("username", $request->search);
            }

        }
        $this->fyInit(route('web.remit.logs'), 10)->fyCalc($query->count(), $index);
        $this->data['logs'] = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)
            ->orderBy('status', 'asc')->orderBy('create_time', 'desc')->get();
        $this->fyViewInit($this->data);
        return view('web.remit_logs')->with($this->data);
    }

    /**
     * 注册新会员界面
     */
    public function regUserPage($nid = 0)
    {
        $nuser = MUser::find($nid);
        $this->data['nuser'] = $nuser;
        $this->data['protocol'] = MProtocols::find(1);
        //会员等级
        $vips = VVip::getVipList();
        $this->data['vips'] = empty($vips) ? [] : $vips;
        return view('web.reg_user')->with($this->data);
    }

    /**
     * 注册新的会员
     */
    public function registerAct(Request $request)
    {
        echo 1234;
//        if (!$this->validateReq($request, MUser::regRulesWithMsg(0), MUser::regRulesWithMsg(1))) {
//            $this->data = $this->makeJsCode(1, $this->errors->first());
//            return response()->json($this->data);
//        }
//        //检查会员等级
//        if (!in_array($request->vip, [1, 2, 3, 4, 5])) {
//            $this->data = $this->makeJsCode(1, "注册的会员等级异常！");
//            return response()->json($this->data);
//        }
//
//
//        $user = new MUser();
//
//        //检查会员是否重名
//        if ($user->existUserName($request->username)) {
//            $this->data = $this->makeJsCode(1, "用户名已经存在！");
//            return response()->json($this->data);
//        }
//
//        //检查推荐人
//        $puser = TreeUtil::checkPUserByName($request->pname);
//        if (empty($puser)) {
//            $this->data = $this->makeJsCode(1, "无效的推荐人！");
//            return response()->json($this->data);
//        }
//
//        //检查接点人
//        $addr = MUser::$ADDR_NO;
//        $nuser = TreeUtil::checkNUserByName($request->nname);
//        if (empty($nuser)) {
//            $this->data = $this->makeJsCode(1, "无效的接点人！");
//            return response()->json($this->data);
//        } else {    //判断节点是否有位置
//            $addr = TreeUtil::getNodeAddrByUser($nuser);
//            if ($addr == MUser::$ADDR_NO) {
//                $this->data = $this->makeJsCode(1, "接点人位置已满！");
//                return response()->json($this->data);
//            } elseif ($addr == MUser::$ADDR_B) {
//                if ($nuser->auser()->ok_status == MUser::$STATUS_NOACTIVATED) {
//                    $this->data = $this->makeJsCode(1, "接点人A区未激活，不可挂载B区节点！");
//                    return response()->json($this->data);
//                }
//            }
//        }
//        try {
//            DB::transaction(function () use ($request, $puser, $nuser, $addr, &$user) {
//                if ($user->regUser($request, $puser, $nuser, $addr)) {
//                    event(new RegSuccess($user));   //发送注册成功事件通知
//                    $this->data = $this->makeJsCode(0, "注册会员成功！");
//                } else {
//                    DB::rollBack();
//                    $this->data = $this->makeJsCode(1, "注册会员失败！");
//                }
//            });
//        } catch (Exception $e) {
//            $this->data = $this->makeJsCode(1, "注册会员失败！");
//        }
//        return response()->json($this->data);
    }

    /**
     * 会员列表
     * $flag = 1 未激活的报单会员
     */
    public function usersPage(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('web.users'), 10, $request->getQueryString());
        $query = (new MUser())->query();
        if (!empty($request->search)) {//搜索条件
            $query = $query->where("username", $request->search);
        }


        $query = $query->where("ok_status", MUser::$STATUS_NOACTIVATED)->where('bdzx', ss('uid'))->orderBy('reg_time', 'desc');

        $this->fyCalc($query->count(), $index);
        $this->data['users'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->get();

        $this->fyViewInit($this->data);
        //会员
        $this->data['self'] = MUser::find(ss('uid'));
        return view('web.users')->with($this->data);
    }

    /**
     * 已激活用户列表
     */
    public function actUserList(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('web.active-users.list'), 10, $request->getQueryString());
        $query = (new MUser())->query();
        if (!empty($request->search)) {//搜索条件
            $query = $query->where("username", $request->search);
        }

        $query = $query->where("ok_status", MUser::$STATUS_ACTIVATED)->where("bdzx", ss('uid'))->orderBy('reg_time', 'desc');

        $this->fyCalc($query->count(), $index);
        $this->data['users'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->get();

        $this->fyViewInit($this->data);
        return view('web.actuser_list')->with($this->data);
    }

    /**
     * 推荐子会员
     */
    public function pUserList(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('web.p-users.list'), 10, $request->getQueryString());
        $query = (new MUser())->query();
        if (!empty($request->search)) {//搜索条件
            $query = $query->where("username", $request->search);
        }


        $query = $query->where("pid", ss('uid'))->orderBy('reg_time', 'desc');

        $this->fyCalc($query->count(), $index);
        $this->data['users'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->get();

        $this->fyViewInit($this->data);
        return view('web.puser_list')->with($this->data);
    }

    /**
     * 申请报单中心界面
     */
    public function bdzxPage()
    {
        $this->data['user'] = MUser::find(ss('uid'));
        $this->data['bdzxLog'] = MBdzxLog::where('uid', ss('uid'))->orderBy('time', 'desc')->get();
        return view('web.apply_bdzx')->with($this->data);
    }

    /**
     * 申请报单中心逻辑处理
     */
    public function bdzxAct(Request $request)
    {
        if (cv("switch.apply_bdzx") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

        $me = MUser::find(ss('uid'));
        if ($me->safepass != $request->safepass) {
            $this->data = $this->makeJsCode(1, '交易密码验证失败！');
            return response()->json($this->data);
        }

        //检查用户状态
        if ($me->ok_status == MUser::$STATUS_NOACTIVATED) {
            $this->data = $this->makeJsCode(1, '用户未激活不能申请报单中心！');
            return response()->json($this->data);
        }

        //检查报单中心状态
        if ($me->bdzx_status == MUser::$BDZX_YES) {
            $this->data = $this->makeJsCode(1, '您已经是报单中心，不可重复开通！');
            return response()->json($this->data);
        }
        if ($me->bdzx_status == MUser::$BDZX_APPLY) {
            $this->data = $this->makeJsCode(1, '您已经申请报单中心，请耐心等待！');
            return response()->json($this->data);
        }

        //检查账户余额
        $me_wallet = $me->wallet;
//        if ($me_wallet->w1 < cache('kv_bdzx_money')) {
//            $this->data = $this->makeJsCode(1, '您的账户余额不足！');
//            return response()->json($this->data);
//        }
        if ($request->payWhat == 1 && $me_wallet->w1 < cv("bonus.bdzx_money")) {
            $this->data = $this->makeJsCode(1, '你的奖金币余额不足,请充值');
            return response()->json($this->data);
        }

        if ($request->payWhat == 2 && ($me_wallet->w1 < getBdb(0) || $me_wallet->w2 < getBdb(1))) {
            $this->data = $this->makeJsCode(1, '你的奖金币或者报单币余额不足,请充值');
            return response()->json($this->data);
        }

        //开通报单中心
        try {
            DB::transaction(function () use (&$me, &$request) {
                if ($me->applyBdzx($request->payWhat)) {
                    $this->data = $this->makeJsCode(0, "申请成功！");
                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "申请失败！");
                }
            });
        } catch (Exception $exception) {
            $this->data = $this->makeJsCode(1, "申请失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 报单中心拒绝内容
     */
    public function bdzxLog($id)
    {
        $bdzx = MBdzxLog::find($id);
        if (!empty($bdzx)) {
            return $bdzx->result;
        }
    }

    /**
     * 会员节点关系图
     */
    public function nodeTreePage(Request $request, $uid = 0)
    {
        $user = MUser::find($uid);
        $me = MUser::find(ss('uid'));
        if (!empty($request->search)) {//搜索条件
            $user = MUser::where('username', $request->search)->first();
        }

        if (empty($user)) {
//            $this->data = $this->makeJsCode(1, "您无权查看您的上级会员！");
//            request()->ss()->flash('code', $this->data['code']);
//            request()->ss()->flash('msg', $this->data['msg']);
            $this->data['user'] = $me;
        } elseif ($user->ntree < $me->ntree) {
            $this->data = $this->makeJsCode(1, "您无权查看您的上级会员！");
            return back()->with($this->data);
        } else {
            $this->data['user'] = $user;
        }
        return view('web.node_tree')->with($this->data);
    }

    /**
     * 会员推荐关系图
     * @param Request $request
     * @return $this
     */
    public function zTreePage(Request $request)
    {
        $user = MUser::where('username', $request->name)->first();
        $me = MUser::find(ss('uid'));

        if (empty($request->name) || empty($user)) {
            $user = $me;
        } elseif ($user->ptree < $me->ptree) {
            $this->data = $this->makeJsCode(1, "您无权查看您的上级推荐会员！");
            return back()->with($this->data);
        }

        $childs = new Collection();
        $childs->add($user);

        $cids = TreeUtil::getPChildsByUser($user);

        foreach ($cids as $cid) {
            $child = MUser::find($cid);
            $childs->add($child);
        }

        $this->data['user'] = $childs;
        return view('web.node_zTree')->with($this->data);
    }

    /**
     * @return $this 会员升级页面
     */

    public function upUserPage()
    {
        $this->data['user'] = MUser::find(ss('uid'));
//        $this->data['vip_awards'] =MVip_award::all();
        $this->data['vip_up_logs'] = MVip_up_log::where("uid", ss('uid'))->orderBy('time', 'desc')->get();
        //会员等级
        $vips = VVip::getVipList();
        $this->data['vips'] = empty($vips) ? [] : $vips;
        return view('web.upUser')->with($this->data);
    }

    /**
     * @param Request $request 执行会员升级的动作
     * @return \Illuminate\Http\JsonResponse
     */

    public function upUserSave(Request $request)
    {
        if (!$request->has(['vip_up', 'wallet', 'safepass'])) {
            $this->data = $this->makeJsCode(1, "填写信息不完整");
            return response()->json($this->data);

        }

        $user = MUser::find(ss('uid'));
        if ($user->safepass !== $request->safepass) {
            $this->data = $this->makeJsCode(1, "交易密码不正确");
            return response()->json($this->data);
        }
        $method = $request->wallet; //钱包类型

//        $wallet2 = $user->wallet["w" . "$method"];
//        $vip_up_money = uVipByMoney($request->vip_up);
        if ($method == 1) {
            $wallet2 = $user->wallet->w1;
        } elseif ($method == 2) {
            $wallet2 = $user->wallet->w2;
        } elseif ($method == 3) {
            $wallet2 = $user->wallet->w3;
        }
        $vip_up_money = VVip::attrBySlug($request->vip_up)[MUser::$ATTR_ACTIVE];
        if ($vip_up_money > $wallet2) {
            $this->data = $this->makeJsCode(1, "钱包余额不足,升级失败!!!");
            return response()->json($this->data);
        }

        $pre_vip_slug = $user->vip_slug;  //原来的会员标识
        $new_vip_slug = $request->vip_up; //后来的会员标识
        $pre_vip_point = VVip::attrBySlug($pre_vip_slug)[MUser::$ATTR_POINT];   //获取原来的会员权重
        $new_Vip_point = VVip::attrBySlug($new_vip_slug)[MUser::$ATTR_POINT];  //获取现在的会员权重
        if ($pre_vip_point > $new_Vip_point) {
            $this->data = $this->makeJsCode(1, "升级不能小于原先等级!!!");
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use ($user, $method, $pre_vip_slug, $new_vip_slug, $vip_up_money) {
                if ($user->upVip($new_vip_slug) && $user->wallet->upVip($method, $vip_up_money)) {
                    if (MVip_up_log::vip_up_log(ss('uid'), $pre_vip_slug, $new_vip_slug, $method)) {
                        $this->data = $this->makeJsCode("0", "升级用户成功");
                    }

                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode("1", "升级用户失败");
                }
            });
        } catch (Exception $e) {
            DB::rollBack();
            $this->data = $this->makeJsCode("1", "升级用户失败");
        }
        return response()->json($this->data);
    }

    /**
     * 我的个人信息页面
     */
    public function myInfoPage()
    {
        $this->data['user'] = MUser::find(ss('uid'));
        return view('web.information')->with($this->data);
    }

    /**
     * 生成推广二维码
     */
    public function produceQrcode()
    {
        $user = MUser::find(ss('uid'));
        $info = route('reg.page') . '/' . $user->no;
        QRUtil::png($info);
    }

    /**
     *  个人信息修改保存
     */
    public function myInfoSave(Request $request)
    {
        if (!$this->validateReq($request, MUser::myInfoRulesWithMsg(0), MUser::myInfoRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $me = MUser::find(ss('uid'));
        if ($me->first == MUser::$FIRST_OK) { //判断是否修改过
            $this->data = $this->makeJsCode(1, '你已修改一次信息不可再次修改！');
            return response()->json($this->data);
        }

        if ($request->hasFile('filePic') && $request->file('filePic')->isValid()) {
            $file = $request->file('filePic');
            $filename = md5_file($file->getPathname()) . "." . $file->getClientOriginalExtension();   //md5 + 扩展名
            $file->move('uploads/imgs/', $filename);
            $pic = '/uploads/imgs/' . $filename;
        } else {
            $pic = $request->pic;
        }
        if ($me->infoSave($request->email, $request->realname, $request->mobile, $request->receipt, $pic)) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 修改密码界面
     */
    public function modifyPassPage()
    {
        return view('web.modify_pass');
    }

    /**
     * 修改密码保存方法
     */
    public function modifyPassSave(Request $request)
    {

        if (!$this->validateReq($request, MUser::modifyPassRulesWithMsg(0), MUser::modifyPassRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $me = MUser::find(ss('uid'));

        //判断是否修改登录密码
        if (intval($request->type) == 1) {
            if ($request->oldpass != $me->userpass) {
                $this->data = $this->makeJsCode(1, '原密码验证失败!');
                return response()->json($this->data);
            }
        } elseif (intval($request->type) == 2) {
            if ($request->oldpass != $me->safepass) {
                $this->data = $this->makeJsCode(1, '原密码验证失败!');
                return response()->json($this->data);
            }
        }

        if ($me->modifyPass($request->type, $request->newpass)) {
            $this->data = $this->makeJsCode(0, '修改密码成功!');
        } else {
            $this->data = $this->makeJsCode(0, '修改密码失败!');
        }

        return response()->json($this->data);
    }

    /**
     * 前台退出当前用户的登录
     */
    public function exitAct()
    {
        $user = new Muser;
        $user->loginStatus($bool = false);
        return redirect()->route('login.page');
    }

    /**
     * 找回密码操作
     */
    public function findPass(Request $request)
    {
        if (!$request->has('username')) {
            $this->data = $this->makeJsCode(1, "请输入您要查找的用户名！");
            return response()->json($this->data);
        }

        $user = MUser::where('username', $request->username)->first();
        if (empty($user) || empty($user->email)) {
            $this->data = $this->makeJsCode(1, "账户未绑定邮箱，无法找回！");
            return response()->json($this->data);
        }

        try {
            Mail::send('system.coms.findpass-template', ['user' => $user], function ($m) use ($user) {
                $m->subject("密码找回邮件，请查收！")
                    ->from(env('MAIL_USERNAME'), cv('website.site_name'))
                    ->to($user->email);
            });
            $this->data = $this->makeJsCode(0, "密码已发送至您的绑定邮箱！");
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "邮件发送失败，请重新尝试！");
        }

        return response()->json($this->data);
    }

}